<template>
  <div>
    <el-card class="box-card">
      <div class="input_box">
        <!-- 搜索 -->
        <el-input
          placeholder="请输入内容"
          v-model="query.query"
          class="in"
          clearable
          @input="onClickSearch"
        >
          <!-- 搜索点击按钮 -->
        </el-input>
        <div class="button">
          <el-button icon="el-icon-search" @click="onClickSearch"></el-button>
        </div>
        <!-- 添加用户按钮 -->
        <div class="add">
          <el-button type="primary" @click="onopenThe">添加用户</el-button>
        </div>
      </div>

      <!-- 渲染表格 -->
      <div class="table">
        <el-table :data="userlist" border style="width: 100%" size="mini">
          <el-table-column type="index" label="#" width="50"> </el-table-column>
          <el-table-column prop="username" label="姓名" width="180">
          </el-table-column>
          <el-table-column prop="email" label="邮箱"> </el-table-column>
          <el-table-column prop="mobile" label="电话"> </el-table-column>
          <el-table-column prop="role_name" label="角色"> </el-table-column>
          <el-table-column prop="mg_state" label="状态">
            <!-- 状态插槽 -->
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="change(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间">
            <!-- 创建时间插槽 -->
            <template slot-scope="scope">
              <div>
                {{ scope.row.create_time | dateTime }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="" label="操作" width="180">
            <template slot-scope="scope">
              <!-- 编辑按钮 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="editOpenThe(scope.row)"
              ></el-button>

              <!-- 删除按钮 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="Delete(scope.row)"
              ></el-button>
              <!-- 分配角色按钮 -->
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="permissions(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="paging_box">
          <!-- 分页 -->
          <el-pagination
            :current-page="pagenum"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="parseInt(this.total)"
            @current-change="currentChange"
            @size-change="sizeChange"
          >
          </el-pagination>
          <!-- 添加弹框 -->
          <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
            <span>
              <el-form
                :model="addUserDiaData"
                ref="ruleForm"
                :rules="addUserDiaRules"
                label-width="100px"
                class="demo-ruleForm"
              >
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="addUserDiaData.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input v-model="addUserDiaData.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="addUserDiaData.email"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                  <el-input v-model="addUserDiaData.mobile"></el-input>
                </el-form-item>
              </el-form>
            </span>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="onClickAdd">确 定</el-button>
            </span>
          </el-dialog>
          <!-- 编辑弹框 -->
          <el-dialog
            title="编辑用户"
            :visible.sync="editDialogVisible"
            width="50%"
          >
            <span>
              <el-form
                :model="addUserDiaData"
                ref="ruleForm"
                :rules="addUserDiaRules"
                label-width="100px"
                class="demo-ruleForm"
              >
                <el-form-item label="用户名" prop="">
                  <el-input
                    v-model="addUserDiaData.username"
                    :disabled="true"
                  ></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="addUserDiaData.email"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                  <el-input v-model="addUserDiaData.mobile"></el-input>
                </el-form-item>
              </el-form>
            </span>
            <span slot="footer" class="dialog-footer">
              <el-button @click="editDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="editDetermine">确 定</el-button>
            </span>
          </el-dialog>
          <!-- 分类权限弹框-->
          <el-dialog title="分配角色" :visible.sync="Setupthe" width="50%">
            <span>
              <div class="classify_box">
                <div>
                  <p>当前的用户：{{ this.set.username }}</p>
                </div>
                <div>
                  <p>当前的角色：{{ this.set.role_name }}</p>
                </div>
                <div>
                  <p class="js">
                    <span> 分配新角色：</span>
                    <el-select
                      v-model="roleid"
                      slot="prepend"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in showrolelist"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </p>
                </div>
              </div>
            </span>
            <span slot="footer" class="dialog-footer">
              <el-button @click="Setupthe = false">取 消</el-button>
              <el-button type="primary" @click="onClickOK">确 定</el-button>
            </span>
          </el-dialog>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import _ from "lodash";
import {
  users,
  usersAdd,
  Edituser,
  Deleteuser,
  stateuser,
  Rolelist,
  Distribution,
} from "../../http/api";
export default {
  data() {
    //邮箱验证规则
    const checkEmail = (rule, value, callback) => {
      const reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/g; //用户名@xxxx.com.cn
      if (!reg.test(value)) {
        return callback(new Error("邮箱不合法，请输入重新"));
      }

      callback();
    };

    //手机号验证规则
    const checkMobile = (rule, value, callback) => {
      const reg = /^1(3|4|5|6|7|8|9)\d{9}$/g;
      if (!reg.test(value)) {
        return callback(new Error("手机号不合法，请输入重新手机号"));
      }

      callback();
    };
    return {
      currrentUserId: "", //当前用户id
      roleid: "", //当前角色id
      dialogVisible: false, //添加弹框
      editDialogVisible: false, //修改弹框
      Setupthe: false, //分类权限弹框
      userlist: [], //数据渲染
      total: "", //总条数
      pagenum: 1, //当前页
      pagesize: 10, //页面多少数据
      query: {
        //搜索数据
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      // ruleForm: {},
      addUserDiaData: {
        //添加 编辑数据
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      set: {},
      showrolelist: [],
      roleName: "",
      //添加用户对话表单验证规则
      addUserDiaRules: {
        username: [
          { required: true, message: "请填写用户名", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "请输入长度在6到16之间的字符个数",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请填写密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "请输入长度在6到16之间的字符个数",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请填写邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请填写手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  created() {
   //首页列表
    users({ pagenum: this.pagenum, pagesize: this.pagesize }).then((res) => {
      console.log(res);
      // 表格数据
      this.userlist = res.users;
      // 分页总数
      this.total = res.total;
    });
  },
  methods: {
    // 切换每页
    currentChange(val) {
      console.log(val);
      this.pagenum = val;
      users({ pagenum: this.pagenum, pagesize: this.pagesize }).then((res) => {
        console.log(res);
        this.userlist = res.users;
      });
    },
    // 每页页 条数
    sizeChange(val) {
      this.pagesize = val;
      users({ pagenum: this.pagenum, pagesize: this.pagesize }).then((res) => {
        console.log(res);
        this.userlist = res.users;
      });
    },
    // 搜索 把高频事件转变成低频事件,从而提高项目性能,提高用户的体验。
    onClickSearch: _.throttle(function () {
      users(this.query).then((res) => {
        console.log(res);
        this.userlist = res.users;
      });
    }, 1500),
    // onClickSearch() {
    //   console.log(this.query);
    //   users(this.query).then((res) => {
    //     console.log(res);
    //     this.userlist = res.users;
    //   });
    // },
    // 改变状态
    async change(state) {
      console.log(state);
      const stateid = state.id; //用户的id
      const statemg = state.mg_state; //用户的状态
      const res = await stateuser(stateid, statemg); //修改状态接口
      console.log(res);
      users({ pagenum: this.pagenum, pagesize: this.pagesize }).then((res) => {
        console.log(res);
        this.userlist = res.users;
      });
    },
    // 添加
    onopenThe() {
      this.dialogVisible = true;
    },
    async onClickAdd() {
      const res = await usersAdd(this.addUserDiaData);
      console.log(res);
      users({ pagenum: this.pagenum, pagesize: this.pagesize }).then((res) => {
        console.log(res);
        this.userlist = res.users;
      });
      this.dialogVisible = false;
    },
    // 编辑
    editOpenThe(user) {
      console.log(user);
      this.currrentUserId = user.id;
      this.addUserDiaData = user;
      this.editDialogVisible = true;
    },
    async editDetermine() {
      const res = await Edituser(this.currrentUserId, this.addUserDiaData);
      console.log(res);
      this.editDialogVisible = false;

      users({ pagenum: this.pagenum, pagesize: this.pagesize }).then((res) => {
        console.log(res);
        this.userlist = res.users;
      });
    },
    // 删除
    async Delete(de) {
      console.log(de);
      const removeid = de.id;
      console.log(removeid);
      const res = await Deleteuser(removeid);
      console.log(res);

      this.$confirm("您确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          users({ pagenum: this.pagenum, pagesize: this.pagesize }).then(
            (res) => {
              console.log(res);
              this.userlist = res.users;
            }
          );
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 修改角色列表
    async permissions(per) {
      // console.log(per);
      this.Setupthe = true;
      this.set = per;
      this.currrentUserId = per.id;

      // 调用角色列表接口
      const res = await Rolelist();
      console.log("角色列表", res);
      this.showrolelist = res; //渲染多选框
    },
    async onClickOK() {
      console.log(this.roleid);
      console.log(this.currrentUserId);
      const res = await Distribution(this.currrentUserId, { rid: this.roleid });
      this.roleid = "";
      console.log(res);
      users({ pagenum: this.pagenum, pagesize: this.pagesize }).then((res) => {
        console.log(res);
        this.userlist = res.users;
      });
      this.Setupthe = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.el-input__inner {
  border-radius: 0px !important;
}
.input_box {
  width: 100%;
  height: 40px;
  // background-color: rebeccapurple;
  display: flex;
  justify-content: flex-start;
  .in {
    width: 346px;
  }
}
.button {
  .el-button {
    border-radius: 0px !important;
    background-color: #f5f7fa;
  }
}
.add {
  margin-left: 10px;
}
.table {
  margin-top: 15px;
}
.paging_box {
  width: 100%;
  display: flex;
  justify-items: flex-start;
}
.el-dialog__header {
  width: 100%;
  display: flex;
  justify-content: flex-start;
}
.classify_box {
  width: 100%;
  height: 100%;
  div {
    width: 100%;
    height: 30px;
    display: flex;
    justify-content: flex-start;
  }
  .js {
    display: flex;
    span {
      width: 115px;
      margin-top: 10px;
    }
  }
}
</style>